package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;
    @Override
    public void saveRole(Role role) {
        roleMapper.insert(role);
    }

    @Override
    public PageResponse<RoleVo> findByPage(Integer pageNum, Integer pageSize, String roleName) {
        PageHelper.startPage(pageNum,pageSize);
        Page<RoleVo> roleVos = roleMapper.selectByCondition(roleName);
        return PageResponse.of(roleVos,RoleVo.class);
    }

    @Override
    public Set<String> findByRoleId(Long roleId) {
        Set<String> resources = roleResourceMapper.selectByRoleId(roleId);
        return resources;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(RoleDto dto) {
        if (StringUtils.isNotBlank(dto.getRoleName())) {
            Role role = new Role();
            role.setRoleName(dto.getRoleName());
            role.setId(dto.getId());
            role.setDataState(dto.getDataState());
            roleMapper.updateByPrimaryKey(role);
        } else {
            roleResourceMapper.deleteByRoleId(dto.getId());
            List<RoleResource> roleResourceList = new ArrayList<>();
            String[] resourceNos = dto.getCheckedResourceNos();
            if (resourceNos == null || resourceNos.length == 0) {
                return;
            }
            for (String resourceNo : resourceNos) {
                RoleResource roleResource = new RoleResource(dto.getId(), resourceNo, "0");
                roleResourceList.add(roleResource);
            }
            roleResourceMapper.batchInsert(roleResourceList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByRoleId(Long roleId) {
        roleResourceMapper.deleteByRoleId(roleId);
        roleMapper.deleteByPrimaryKey(roleId);
    }
}
